#include "Mouse.h"

ID3D11Texture2D* CreateOffScreenRenderTarget(ID3D11Device* pDevice, ID3D11RenderTargetView* pRTView)
{
	ID3D11Texture2D* pOffScreenRT = NULL;
	ID3D11Resource* pResource = NULL;
	ID3D11Texture2D* pRT = NULL;
	ID3D11DeviceContext* pContext = NULL;
	D3D11_TEXTURE2D_DESC Tex2DDesc;
	HRESULT hr = S_OK;

	pRTView->GetResource(&pResource);

	pRT = (ID3D11Texture2D*)(pResource);
	
	pRT->GetDesc(&Tex2DDesc);
	
	Tex2DDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
	Tex2DDesc.Usage = D3D11_USAGE_STAGING;
	Tex2DDesc.BindFlags = 0;
	hr = pDevice->CreateTexture2D(&Tex2DDesc, NULL, &pOffScreenRT);

	pDevice->GetImmediateContext(&pContext);

	pContext->CopyResource(pOffScreenRT, pRT);

	return pOffScreenRT;
}

//TODO no unmapping is occuring here
ID3D11Texture2D* GetRenderTargetCopy(ID3D11Device* pDevice, UINT RTIndex)
{
	UINT NumViews = RTIndex + 1;
	ID3D11DeviceContext* pContext = NULL;
	ID3D11RenderTargetView* pRTViews[8];

	pDevice->GetImmediateContext(&pContext);
	pContext->OMGetRenderTargets(NumViews, pRTViews, NULL);

	return CreateOffScreenRenderTarget(pDevice, pRTViews[RTIndex]);
	
}

void CMouse::Move( int x, int y )
{
	m_pos = IntPoint(x,y);
}

int CMouse::SelectObject( ID3D11Device* pDevice, int x, int y )
{
	ID3D11DeviceContext* pContext = NULL;
	ID3D11Texture2D* pRT = NULL;
	D3D11_MAPPED_SUBRESOURCE RTInfo; 
	pRT = GetRenderTargetCopy(pDevice, 1);
	pDevice->GetImmediateContext(&pContext);
	pContext->Map(pRT, 0, D3D11_MAP_READ, 0, &RTInfo);

	BYTE* pTexels = (BYTE*)RTInfo.pData;
	BYTE* pTexel = pTexels + x * sizeof(SObjectIndex) + y * RTInfo.RowPitch;
	SObjectIndex* pIndex = (SObjectIndex*)pTexel;

	return pIndex->TerrainIndex;
}

